"""
The MIT License (MIT)
Copyright © 2021 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-video-stream
"""
from PIL import ImageGrab, Image


class Capture(object):
	def __init__(self, threshold:int=115):
		self.__image = None
		self.__table = self.__get_bin_table(threshold)

	def get_desktop_data(self, resize_box:tuple=(128, 64)):
		try:
			self.__image = ImageGrab.grab()
		except OSError as ose:
			if str(ose) == 'screen grab failed':
				return None

		self.__image = self.__image.convert("L")
		self.__image = self.__image.resize(resize_box)

		self.__image = self.__image.point(self.__table, '1')
		self.__image = self.__image.transpose(Image.FLIP_LEFT_RIGHT)

		return self.__get_buffer()

	def __get_buffer(self):
		data = list(self.__image.getdata())
		buffer = b''

		width, height = self.__image.size
		bytes_per_row = int(width / 8)

		def int_to_str(value):
			return '0' if value == 0 else '1'

		for y in range(height):
			temp = map(int_to_str, data[y * width:y * width + width])
			buffer += int(''.join(temp), 2).to_bytes(bytes_per_row, 'little')

		return buffer

	def __get_bin_table(self, threshold=115):
		'''获取灰度转二值的映射表，0 表示黑色，1 表示白色'''
		def append(value):
			return 0 if value < threshold else 1

		return list(map(append, range(256)))


# for testing
if __name__ == '__main__':
	capture = Capture()
	a=capture.get_desktop_data()
	print(len(a), a)
